package com.ruoyi.vbze.service.impl;

import java.util.List;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.vbze.domain.Block;
import com.ruoyi.vbze.mapper.FieldMapper;
import com.ruoyi.vbze.domain.Field;
import com.ruoyi.vbze.service.IFieldService;

/**
 * 大田管理Service业务层处理
 * 
 * @author vbze
 * @date 2023-02-22
 */
@Service
public class FieldServiceImpl implements IFieldService 
{

    private static final Logger log = LoggerFactory.getLogger(FieldServiceImpl.class);

    @Autowired
    private FieldMapper fieldMapper;

    /**
     * 查询大田管理
     * 
     * @param id 大田管理主键
     * @return 大田管理
     */
    @Override
    public Field selectFieldById(Long id)
    {
        return fieldMapper.selectFieldById(id);
    }

    /**
     * 查询大田管理列表
     * 
     * @param field 大田管理
     * @return 大田管理
     */
    @Override
    public List<Field> selectFieldList(Field field)
    {
        return fieldMapper.selectFieldList(field);
    }

    /**
     * 新增大田管理
     * 
     * @param field 大田管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertField(Field field)
    {
        field.setCreateTime(DateUtils.getNowDate());
        field.setLastEditTime(DateUtils.getNowDate());
        int rows = fieldMapper.insertField(field);
        insertBlock(field);
        return rows;
    }

    /**
     * 修改大田管理
     * 
     * @param field 大田管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateField(Field field)
    {
        fieldMapper.deleteBlockByFieldNumber(field.getFieldNumber());
        insertBlock(field);
        field.setLastEditTime(DateUtils.getNowDate());
        return fieldMapper.updateField(field);
    }

    /**
     * 批量删除大田管理
     * 
     * @param ids 需要删除的大田管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteFieldByIds(Long[] ids)
    {
        String[] fieldNumbers = fieldMapper.selectFieldNumbersByIds(ids);
        fieldMapper.deleteBlockByFieldNumbers(fieldNumbers);
        return fieldMapper.deleteFieldByIds(ids);
    }

    /**
     * 删除大田管理信息
     * 
     * @param id 大田管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteFieldById(Long id)
    {
        fieldMapper.deleteBlockByFieldNumber(selectFieldById(id).getFieldNumber());
        return fieldMapper.deleteFieldById(id);
    }

    /**
     * 新增地块管理信息
     * 
     * @param field 大田管理对象
     */
    public void insertBlock(Field field)
    {
        List<Block> blockList = field.getBlockList();
//        Long id = field.getId();
        String fieldNumber = field.getFieldNumber();
        if (StringUtils.isNotNull(blockList))
        {
            List<Block> list = new ArrayList<Block>();
            for (Block block : blockList)
            {
                block.setFieldNumber(fieldNumber);
                list.add(block);
            }
            if (list.size() > 0)
            {
                fieldMapper.batchBlock(list);
            }
        }
    }



    /**
     * 导入大田数据
     *
     * @param fieldList 大田数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importField(List<Field> fieldList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(fieldList) || fieldList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
//        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (Field field : fieldList)
        {
            try
            {
                // 验证是否存在这个地块
//                SysUser u = userMapper.selectUserByUserName(block.getUserName());
                Field f = fieldMapper.selectFieldByFieldNumber(field.getFieldNumber());
                if (StringUtils.isNull(f))
                {
//                    BeanValidators.validateWithException(validator, block);
//                    block.setPassword(SecurityUtils.encryptPassword(password));
                    field.setCreateBy(operName);
                    field.setLastEditor(operName);
                    field.setUpdateBy(operName);
                    this.insertField(field);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、大田 " + field.getFieldNumber() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
//                    BeanValidators.validateWithException(validator, block);
//                    checkUserAllowed(block);
//                    checkUserDataScope(block.getUserId());
//                    block.setUpdateBy(operName);
                    field.setLastEditor(operName);
                    field.setUpdateBy(operName);
                    this.updateField(field);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、大田 " + field.getFieldNumber() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、大田 " + field.getFieldNumber() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、大田 " + field.getFieldNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


}
